<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>shiro缓存机制 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Shiro 的缓存机制缓存机制Shiro 提供了类似于 Spring 的 Cache 抽象，即 Shiro 本身不实现 Cache，但是对 Cache 进行了又抽象，方便更换不同的底层 Cache 实现">
<meta name="keywords" content="shiro">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro缓存机制">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-03-17-shiro的缓存机制/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Shiro 的缓存机制缓存机制Shiro 提供了类似于 Spring 的 Cache 抽象，即 Shiro 本身不实现 Cache，但是对 Cache 进行了又抽象，方便更换不同的底层 Cache 实现">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-11-01T14:24:04.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro缓存机制">
<meta name="twitter:description" content="Shiro 的缓存机制缓存机制Shiro 提供了类似于 Spring 的 Cache 抽象，即 Shiro 本身不实现 Cache，但是对 Cache 进行了又抽象，方便更换不同的底层 Cache 实现">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-03-17-shiro的缓存机制" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-03-17-shiro的缓存机制/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      shiro缓存机制
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="Shiro-的缓存机制"><a href="#Shiro-的缓存机制" class="headerlink" title="Shiro 的缓存机制"></a>Shiro 的缓存机制</h2><h3 id="缓存机制"><a href="#缓存机制" class="headerlink" title="缓存机制"></a>缓存机制</h3><p>Shiro 提供了类似于 Spring 的 Cache 抽象，即 Shiro 本身不实现 Cache，但是对 Cache 进行了又抽象，方便更换不同的底层 Cache 实现</p>
<a id="more"></a>
<p><strong>Shiro 提供的 Cache 接口</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public interface Cache&lt;K, V&gt; &#123;</span><br><span class="line">    //根据Key获取缓存中的值</span><br><span class="line">    public V get(K key) throws CacheException;</span><br><span class="line">    //往缓存中放入key-value，返回缓存中之前的值</span><br><span class="line">    public V put(K key, V value) throws CacheException; </span><br><span class="line">    //移除缓存中key对应的值，返回该值</span><br><span class="line">    public V remove(K key) throws CacheException;</span><br><span class="line">    //清空整个缓存</span><br><span class="line">    public void clear() throws CacheException;</span><br><span class="line">    //返回缓存大小</span><br><span class="line">    public int size();</span><br><span class="line">    //获取缓存中所有的key</span><br><span class="line">    public Set&lt;K&gt; keys();</span><br><span class="line">    //获取缓存中所有的value</span><br><span class="line">    public Collection&lt;V&gt; values();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>Shiro 提供的 CacheManager 接口</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface CacheManager &#123;</span><br><span class="line">    //根据缓存名字获取一个Cache</span><br><span class="line">    public &lt;K, V&gt; Cache&lt;K, V&gt; getCache(String name) throws CacheException;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>Shiro 还提供了 CacheManagerAware 用于注入 CacheManager</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface CacheManagerAware &#123;</span><br><span class="line">    //注入CacheManager</span><br><span class="line">    void setCacheManager(CacheManager cacheManager);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Shiro 内部相应的组件（DefaultSecurityManager）会自动检测相应的对象（如 Realm）是否实现了 CacheManagerAware 并自动注入相应的 CacheManager。</p>
<p>本章用例使用了与第六章的代码。</p>
<h2 id="Realm-缓存"><a href="#Realm-缓存" class="headerlink" title="Realm 缓存"></a>Realm 缓存</h2><p>Shiro 提供了 CachingRealm，其实现了 CacheManagerAware 接口，提供了缓存的一些基础实现；另外 AuthenticatingRealm 及 AuthorizingRealm 分别提供了对 AuthenticationInfo 和 AuthorizationInfo 信息的缓存。</p>
<p><strong>ini 配置</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">userRealm=com.github.zhangkaitao.shiro.chapter11.realm.UserRealm</span><br><span class="line">userRealm.credentialsMatcher=$credentialsMatcher</span><br><span class="line">userRealm.cachingEnabled=true</span><br><span class="line">userRealm.authenticationCachingEnabled=true</span><br><span class="line">userRealm.authenticationCacheName=authenticationCache</span><br><span class="line">userRealm.authorizationCachingEnabled=true</span><br><span class="line">userRealm.authorizationCacheName=authorizationCache</span><br><span class="line">securityManager.realms=$userRealm</span><br><span class="line">cacheManager=org.apache.shiro.cache.ehcache.EhCacheManager</span><br><span class="line">cacheManager.cacheManagerConfigFile=classpath:shiro-ehcache.xml</span><br><span class="line">securityManager.cacheManager=$cacheManager&amp;nbsp;</span><br></pre></td></tr></table></figure>
<ul>
<li>userRealm.cachingEnabled：启用缓存，默认 false；</li>
<li>userRealm.authenticationCachingEnabled：启用身份验证缓存，即缓存 AuthenticationInfo 信息，默认 false；</li>
<li>userRealm.authenticationCacheName：缓存 AuthenticationInfo 信息的缓存名称；</li>
<li>userRealm. authorizationCachingEnabled：启用授权缓存，即缓存 AuthorizationInfo 信息，默认 false；</li>
<li>userRealm. authorizationCacheName：缓存 AuthorizationInfo 信息的缓存名称；</li>
<li>cacheManager：缓存管理器，此处使用 EhCacheManager，即 Ehcache 实现，需要导入相应的 Ehcache 依赖，请参考 pom.xml；</li>
</ul>
<p>因为测试用例的关系，需要将 Ehcache 的 CacheManager 改为使用 VM 单例模式： this.manager = new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream())； 改为 this.manager = net.sf.ehcache.CacheManager.create(getCacheManagerConfigFileInputStream())；</p>
<h4 id="测试用例"><a href="#测试用例" class="headerlink" title="测试用例"></a>测试用例</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void testClearCachedAuthenticationInfo() &#123;</span><br><span class="line">    login(u1.getUsername(), password);</span><br><span class="line">    userService.changePassword(u1.getId(), password + &quot;1&quot;);</span><br><span class="line">    RealmSecurityManager securityManager =</span><br><span class="line">     (RealmSecurityManager) SecurityUtils.getSecurityManager();</span><br><span class="line">    UserRealm userRealm = (UserRealm) securityManager.getRealms().iterator().next();   userRealm.clearCachedAuthenticationInfo(subject().getPrincipals());</span><br><span class="line">    login(u1.getUsername(), password + &quot;1&quot;);</span><br><span class="line">&#125;&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>首先登录成功（此时会缓存相应的 AuthenticationInfo），然后修改密码；此时密码就变了；接着需要调用 Realm 的 clearCachedAuthenticationInfo 方法清空之前缓存的 AuthenticationInfo；否则下次登录时还会获取到修改密码之前的那个 AuthenticationInfo；</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void testClearCachedAuthorizationInfo() &#123;</span><br><span class="line">    login(u1.getUsername(), password);</span><br><span class="line">    subject().checkRole(r1.getRole());</span><br><span class="line">    userService.correlationRoles(u1.getId(), r2.getId());</span><br><span class="line">    RealmSecurityManager securityManager =</span><br><span class="line">      (RealmSecurityManager) SecurityUtils.getSecurityManager();</span><br><span class="line">    UserRealm userRealm = (UserRealm)securityManager.getRealms().iterator().next();   userRealm.clearCachedAuthorizationInfo(subject().getPrincipals());</span><br><span class="line">    subject().checkRole(r2.getRole());</span><br><span class="line">&#125;&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>和之前的用例差不多；此处调用 Realm 的 clearCachedAuthorizationInfo 清空之前缓存的 AuthorizationInfo；</p>
<p>另外还有 clearCache，其同时调用 clearCachedAuthenticationInfo 和 clearCachedAuthorizationInfo，清空 AuthenticationInfo 和 AuthorizationInfo。</p>
<p>UserRealm 还提供了 clearAllCachedAuthorizationInfo、clearAllCachedAuthenticationInfo、clearAllCache，用于清空整个缓存。</p>
<p>在某些清空下这种方式可能不是最好的选择，可以考虑直接废弃 Shiro 的缓存，然后自己通过如 AOP 机制实现自己的缓存；可以参考： <a href="https://github.com/zhangkaitao/es/tree/master/web/src/main/java/com/sishuok/es/extra/aop" target="_blank" rel="noopener">https://github.com/zhangkaitao/es/tree/master/web/src/main/java/com/sishuok/es/extra/aop</a></p>
<p>另外如果和 Spring 集成时可以考虑直接使用 Spring 的 Cache 抽象，可以考虑使用 SpringCacheManagerWrapper，其对 Spring Cache 进行了包装，转换为 Shiro 的 CacheManager 实现：<br><a href="https://github.com/zhangkaitao/es/blob/master/web/src/main/java/org/apache/shiro/cache/spring/SpringCacheManagerWrapper.java" target="_blank" rel="noopener">https://github.com/zhangkaitao/es/blob/master/web/src/main/java/org/apache/shiro/cache/spring/SpringCacheManagerWrapper.java</a></p>
<h2 id="Session-缓存"><a href="#Session-缓存" class="headerlink" title="Session 缓存"></a>Session 缓存</h2><p>当我们设置了 SecurityManager 的 CacheManager 时，如：</p>
<p><code>securityManager.cacheManager=$cacheManager</code></p>
<p>当我们设置 SessionManager 时：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sessionManager=org.apache.shiro.session.mgt.DefaultSessionManager</span><br><span class="line">securityManager.sessionManager=$sessionManager&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>如 securityManager 实现了 SessionsSecurityManager，其会自动判断 SessionManager 是否实现了 CacheManagerAware 接口，如果实现了会把 CacheManager 设置给它。然后 sessionManager 会判断相应的 sessionDAO（如继承自 CachingSessionDAO）是否实现了 CacheManagerAware，如果实现了会把 CacheManager 设置给它；如第九章的 MySessionDAO 就是带缓存的 SessionDAO；其会先查缓存，如果找不到才查数据库。</p>
<p>对于 CachingSessionDAO，可以通过如下配置设置缓存的名称：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sessionDAO=com.github.zhangkaitao.shiro.chapter11.session.dao.MySessionDAO</span><br><span class="line">sessionDAO.activeSessionsCacheName=shiro-activeSessionCache&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>activeSessionsCacheName 默认就是 shiro-activeSessionCache。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-03-17-shiro的缓存机制/" data-id="cjoztxu3b00131wijax6550dh" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/shiro/">shiro</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-03-17-shiro 记住我/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          shiro记住我
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-03-19-shiro综合实例/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">shiro综合实例</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>